package vaccine.appointment.system.common.interceptor;

import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import vaccine.appointment.system.common.annotation.RequireRole;
import vaccine.appointment.system.common.errorcode.CommonErrorCode;
import vaccine.appointment.system.common.exception.CommonException;
import vaccine.appointment.system.common.utils.JWTUtil;
import vaccine.appointment.system.user.enums.IdentityInfoEnum;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

/**
 * 权限拦截器
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是方法处理器，直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;

        // 检查方法或类上是否有@RequireRole注解
        RequireRole methodAnnotation = handlerMethod.getMethodAnnotation(RequireRole.class);
        RequireRole classAnnotation = handlerMethod.getBeanType().getAnnotation(RequireRole.class);

        // 如果没有权限注解，直接放行
        if (methodAnnotation == null && classAnnotation == null) {
            return true;
        }

        // 获取JWT token
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            throw new CommonException(CommonErrorCode.UNAUTHORIZED);
        }

        // 去掉"Bearer "前缀
        token = token.substring(7);

        // 解析token
        Claims claims = JWTUtil.parseJWT(token);
        if (claims == null) {
            throw new CommonException(CommonErrorCode.UNAUTHORIZED);
        }

        // 获取用户角色
        Integer identityInfo = (Integer) claims.get("identityInfo");
        if (identityInfo == null) {
            throw new CommonException(CommonErrorCode.UNAUTHORIZED);
        }

        // 检查权限
        RequireRole requireRole = methodAnnotation != null ? methodAnnotation : classAnnotation;
        IdentityInfoEnum[] requiredRoles = requireRole.value();

        boolean hasPermission = Arrays.stream(requiredRoles)
                .anyMatch(role -> role.getCode().equals(identityInfo));

        if (!hasPermission) {
            throw new CommonException(CommonErrorCode.FORBIDDEN);
        }

        // 将用户信息存入request attribute，供后续使用
        request.setAttribute("userId", claims.get("userId"));
        request.setAttribute("personId", claims.get("personId"));
        request.setAttribute("identityInfo", identityInfo);

        return true;
    }
}

